#pragma once
#include <fstream>
#include <regex>
#include <sys/stat.h>
#include <cassert>
#include "../server.hpp"

std::unordered_map<int, std::string> _statu_msg = {
    {100,  "Continue"},
    {101,  "Switching Protocol"},
    {102,  "Processing"},
    {103,  "Early Hints"},
    {200,  "OK"},
    {201,  "Created"},
    {202,  "Accepted"},
    {203,  "Non-Authoritative Information"},
    {204,  "No Content"},
    {205,  "Reset Content"},
    {206,  "Partial Content"},
    {207,  "Multi-Status"},
    {208,  "Already Reported"},
    {226,  "IM Used"},
    {300,  "Multiple Choice"},
    {301,  "Moved Permanently"},
    {302,  "Found"},
    {303,  "See Other"},
    {304,  "Not Modified"},
    {305,  "Use Proxy"},
    {306,  "unused"},
    {307,  "Temporary Redirect"},
    {308,  "Permanent Redirect"},
    {400,  "Bad Request"},
    {401,  "Unauthorized"},
    {402,  "Payment Required"},
    {403,  "Forbidden"},
    {404,  "Not Found"},
    {405,  "Method Not Allowed"},
    {406,  "Not Acceptable"},
    {407,  "Proxy Authentication Required"},
    {408,  "Request Timeout"},
    {409,  "Conflict"},
    {410,  "Gone"},
    {411,  "Length Required"},
    {412,  "Precondition Failed"},
    {413,  "Payload Too Large"},
    {414,  "URI Too Long"},
    {415,  "Unsupported Media Type"},
    {416,  "Range Not Satisfiable"},
    {417,  "Expectation Failed"},
    {418,  "I'm a teapot"},
    {421,  "Misdirected Request"},
    {422,  "Unprocessable Entity"},
    {423,  "Locked"},
    {424,  "Failed Dependency"},
    {425,  "Too Early"},
    {426,  "Upgrade Required"},
    {428,  "Precondition Required"},
    {429,  "Too Many Requests"},
    {431,  "Request Header Fields Too Large"},
    {451,  "Unavailable For Legal Reasons"},
    {501,  "Not Implemented"},
    {502,  "Bad Gateway"},
    {503,  "Service Unavailable"},
    {504,  "Gateway Timeout"},
    {505,  "HTTP Version Not Supported"},
    {506,  "Variant Also Negotiates"},
    {507,  "Insufficient Storage"},
    {508,  "Loop Detected"},
    {510,  "Not Extended"},
    {511,  "Network Authentication Required"}
};
std::unordered_map<std::string, std::string> _mime_msg = {
    {".aac",        "audio/aac"},
    {".abw",        "application/x-abiword"},
    {".arc",        "application/x-freearc"},
    {".avi",        "video/x-msvideo"},
    {".azw",        "application/vnd.amazon.ebook"},
    {".bin",        "application/octet-stream"},
    {".bmp",        "image/bmp"},
    {".bz",         "application/x-bzip"},
    {".bz2",        "application/x-bzip2"},
    {".csh",        "application/x-csh"},
    {".css",        "text/css"},
    {".csv",        "text/csv"},
    {".doc",        "application/msword"},
    {".docx",       "application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
    {".eot",        "application/vnd.ms-fontobject"},
    {".epub",       "application/epub+zip"},
    {".gif",        "image/gif"},
    {".htm",        "text/html"},
    {".html",       "text/html"},
    {".ico",        "image/vnd.microsoft.icon"},
    {".ics",        "text/calendar"},
    {".jar",        "application/java-archive"},
    {".jpeg",       "image/jpeg"},
    {".jpg",        "image/jpeg"},
    {".js",         "text/javascript"},
    {".json",       "application/json"},
    {".jsonld",     "application/ld+json"},
    {".mid",        "audio/midi"},
    {".midi",       "audio/x-midi"},
    {".mjs",        "text/javascript"},
    {".mp3",        "audio/mpeg"},
    {".mpeg",       "video/mpeg"},
    {".mpkg",       "application/vnd.apple.installer+xml"},
    {".odp",        "application/vnd.oasis.opendocument.presentation"},
    {".ods",        "application/vnd.oasis.opendocument.spreadsheet"},
    {".odt",        "application/vnd.oasis.opendocument.text"},
    {".oga",        "audio/ogg"},
    {".ogv",        "video/ogg"},
    {".ogx",        "application/ogg"},
    {".otf",        "font/otf"},
    {".png",        "image/png"},
    {".pdf",        "application/pdf"},
    {".ppt",        "application/vnd.ms-powerpoint"},
    {".pptx",       "application/vnd.openxmlformats-officedocument.presentationml.presentation"},
    {".rar",        "application/x-rar-compressed"},
    {".rtf",        "application/rtf"},
    {".sh",         "application/x-sh"},
    {".svg",        "image/svg+xml"},
    {".swf",        "application/x-shockwave-flash"},
    {".tar",        "application/x-tar"},
    {".tif",        "image/tiff"},
    {".tiff",       "image/tiff"},
    {".ttf",        "font/ttf"},
    {".txt",        "text/plain"},
    {".vsd",        "application/vnd.visio"},
    {".wav",        "audio/wav"},
    {".weba",       "audio/webm"},
    {".webm",       "video/webm"},
    {".webp",       "image/webp"},
    {".woff",       "font/woff"},
    {".woff2",      "font/woff2"},
    {".xhtml",      "application/xhtml+xml"},
    {".xls",        "application/vnd.ms-excel"},
    {".xlsx",       "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
    {".xml",        "application/xml"},
    {".xul",        "application/vnd.mozilla.xul+xml"},
    {".zip",        "application/zip"},
    {".3gp",        "video/3gpp"},
    {".3g2",        "video/3gpp2"},
    {".7z",         "application/x-7z-compressed"}
};

//工具类
class Util{
    // 工具类，工具函数都应该static
public:
    // 分割字符串
    static ssize_t Split(const std::string &src, const std::string &sep, std::vector<std::string> *array)
    {
        //&是读取，*是修改
        size_t offset = 0;
        while (offset < src.size())
        {
            size_t pos = src.find(sep, offset); // 从src字符串offset处开始查找，
            // 如果找到就返回前一个下标，
            // 没找到返回npos
            if (pos == std::string::npos) // 没有找到特定的字符
            // 将剩余的部分当作一个字串，放入arry中
            {
                if (pos == src.size())
                    break; // 避免越界
                array->emplace_back(src.substr(offset));
                return array->size();
            }
            if (pos == offset)
            { // 生成空字符
                offset += sep.size();
                continue;
            }
            // 正常分割字符
            array->emplace_back(src.substr(offset, pos - offset));
            offset = pos + sep.size();
        }
        return array->size();
    }

    // 读取文件的所有内容，将读取的内容放到一个Buffer中
    static bool ReadFile(const std::string &filename, std::string *buf)
    {
        assert(buf != nullptr);
        std::ifstream ifs(filename, std::ios::binary); // 打开文件，用ifs流
        if (ifs.is_open() == false)
        {
            DBG_LOG("OPEN %s FILE FAILED!!", filename.c_str());
            return false;
        }
        // 定位到最后
        ssize_t fsize = 0;
        ifs.seekg(0, ifs.end); // 跳转读写位置到末尾
        fsize = ifs.tellg();   // 获取当前读写位置相对于起始位置的偏移量，从末尾偏移刚好就是文件大小
        ifs.seekg(0, ifs.beg); // 跳转到起始位置
        buf->resize(fsize);    // 开辟文件大小的空间
        ifs.read(&(*buf)[0], fsize);
        if (ifs.good() == false)
        {
            DBG_LOG("READ %s FILE FAILED!!", filename.c_str());
            ifs.close();
            return false;
        }
        ifs.close();
        return true;
        // 打开文件(读取模式：二进制)
        // 判断是否成功打开
        // 读取末位置seekg
        // 换成文件大小
        // 换回首位置
        // 真正读取(ifs本身read，不是系统调用read)
        // 判断是否读成功good()
    }

    // 向文件写入数据
    static bool WriteFile(const std::string &filename, const std::string &buf)
    {
        // ofstream打开文件(打开模式：追加、二进制)
        std::ofstream ofs(filename, std::ios::binary | std::ios::trunc);
        if (ofs.is_open() == false)
        {
            DBG_LOG("WRITE %s FILE FAILED!!", filename.c_str());
            ofs.close();
            return false;
        }
        // 真正写入文件(write)
        ofs.write(buf.c_str(), buf.size());
        // 判断是否写入成功
        if (ofs.good() == false)
        {
            DBG_LOG("READ %s FILE FAILED!!", filename.c_str());
            ofs.close();
            return false;
        }
        ofs.close();
        return true;
    }

    // url编码，避免url资源路径中查询字符串和http请求中特殊字符产生歧义
    // 编码格式：将特殊字符的ascii值，转换为两个16进制的字符，前缀：%
    // 不编码的特殊字符：.-_~字母、数字
    // RFC3986文档规定，编码格式：%HH
    // w3c文档规定，查询字符串中的空格，要编码成+，解码是+转空格
    static std::string UrlEncode(const std::string url, bool convert_space_to_plus)
    {
        std::string res;
        for (auto &c : url)
        {
            if (c == '.' || c == '-' || c == '_' || c == '~' || isalnum(c))
            {
                res += c;
                continue;
            }
            if (c == ' ' && convert_space_to_plus)
            {
                res += '+';
                continue;
            }
            char tmp[4];
            // snprintf 与 printf比较类似，都是格式化字符串，只不过一个是打印，一个是放到一块空间中
            sprintf(tmp, "%%%02x", c);
            res += tmp;
        }
        return res;
    }

    // 十六进制转十进制
    static char HEXTOI(char c)
    {
        // 返回值用char节省空间
        if (isdigit(c))
        {
            return c - '0';
        }
        if (c >= 'a' && c <= 'f')
        {
            return 10 + c - 'a';
        }
        if (c >= 'A' && c <= 'Z')
        {
            return 10 + c - 'A';
        }
        return -1;
    }
    static std::string UrlDecode(const std::string url, bool convert_space_to_plus)
    {
        std::string res;
        for (int i = 0; i < url.size(); i++)
        {
            if (url[i] == '%' && i + 2 < url.size())
            {
                // 十六进制转为十进制
                // 前一个数字左移四位，加上后一个数字
                char c = HEXTOI(url[i + 1])*16 + HEXTOI(url[i + 2]);
                DBG_LOG("这里可能有问题");
                // 这里可能有问题
                res += c;
                i += 2;
                continue;
            }
            if (url[i] == '+' && convert_space_to_plus)
            {
                res += ' ';
                continue;
            }
            res += url[i];
        }
        return res;
    }

    //响应状态码的描述信息获取
    static std::string StatuDesc(int statu){
        auto it = _statu_msg.find(statu);
        if(it==_statu_msg.end()){
            return "Unknown";
        }
        return it->second;
    }

    //根据文件路径通过后缀名获取文件mime
    static std::string ExtMime(const std::string& path){
        //先获取文件扩展名
        size_t pos = path.find_last_of('.');
        if (pos == std::string::npos){
            return "application/otect-stream";
        }
        std::string ext = path.substr(pos + 1);
        // 根据扩展名，获取mime
        auto it = _mime_msg.find(ext);
        if(it==_mime_msg.end())
            return "application/otect-stream";
        return it->second;
    }
    //判断是否是一个目录
    static bool IsDirectory(const std::string&filename){
        struct stat st;
        int ret = stat(filename.c_str(), &st);
        if (ret < 0)
        {
            return false;
        }
        return S_ISDIR(st.st_mode);
    }
    //判断文件是否是一个普通文件
    static bool IsRegular(const std::string&path){
        struct stat st;
        int ret = stat(path.c_str(), &st);
        if(ret < 0)
            return false;
        return S_ISREG(st.st_mode);
    }
    //判断资源路径是否有效
    static bool ValidPath(const std::string&path){
        //（参数不包含相对根目录）
        //根据'/'分割来计算目录的层数
        //不用判断文件是否存在，因为保证了会调用IsDirectory，不然就重复了
        std::vector<std::string> subdir;
        Split(path, "/", &subdir);
        int depth = 0;
        for(auto &file:subdir){
            if(file=="..")
                depth--;
            else
                depth++;
            if (depth < 0)
                return false;
        }
        return true;
    }
};

class HttpRequest{
public:
    std::string _method;//请求方法
    std::string _path;//请求路径
    std::unordered_map<std::string, std::string> _params;
    std::string _version;                                 // HTTP版本
    std::unordered_map<std::string, std::string> _headers;//头部
    std::string _body;//正文
    std::smatch _matches;//资源路径的正则提取数据
    

public:
    HttpRequest():_version("HTTP/1.1"){}
public:
    //重置
    void ReSet(){
        _method.clear();
        _path.clear();
        _params.clear();
        _version = "HTTP/1.1";
        _headers.clear();
        _body.clear();
        std::smatch match;//(RAII)
        _matches.swap(match);
    }
    //插入头部字段
    void SetHeader(const std::string&key,const std::string&val){
        _headers.insert({key, val});
    }
    //查询是否有某个头部字段的值
    bool HasHeader(const std::string&key)const {
        auto it = _headers.find(key);
        if(it==_headers.end())
            return false;
        return true;
    }
    //获取指定头部字段
    std::string GetHeader(const std::string& key)const{
        auto it = _headers.find(key);
        if(it==_headers.end()){
            int a = 1;
            return "";
        }
        std::string val = it->second;
        return it->second;
    }
    //插入查询字符串
    void SetParam(const std::string& key,const std::string & val){
        _params.insert({key, val});
    }
    //查询是否有某个查询字符串的值
    bool HasParam(const std::string&key){
        auto it = _params.find(key);
        return it != _params.end();
    }
    //获取指定查询字符串的值
    std::string GetParam(const std::string& key){
        auto it = _params.find(key);
        if(it == _params.end())
            return "";
        return it->second;
    }
    //获取正文长度
    size_t ContentLength() const{
        bool ret = HasHeader("Content-Length");
        if(ret==false)
            return 0;
        std::string clen = GetHeader("Content-Length");
        return std::stoi(clen);
    }
    //判断是否是短链接
    bool Close()const{
        // 没有Connection字段，或者有Connection但是值是close，则都是短链接，否则就是长连接
        bool a1 = HasHeader("Connection");
        bool a2 = (GetHeader("Connection") == "keep-alive");
        if (a1 && a2)
        {
            return false;
        }
        return true;
    }
};


class HttpResponse{
public:
    int _statu;
    std::unordered_map<std::string, std::string> _headers;
    std::string _body;
    std::string _redirect_url;
    bool _redirect_flag;
public:
    HttpResponse() : _statu(200), _redirect_flag(false) {}
    HttpResponse(int statu) : _statu(statu), _redirect_flag(false) {}
    void ReSet(){
        _headers.clear();
        _body.clear();
        _statu = 200;
        _redirect_url.clear();
        _redirect_flag = false;
    }
    // 插入头部字段
    void SetHeader(const std::string &key, const std::string &val)
    {
        _headers.insert({key, val});
    }
    // 查询是否有某个头部字段的值
    bool HasHeader(const std::string &key)const
    {
        auto it = _headers.find(key);
        if(it==_headers.end())
            return false;
        return true;
    }
    // 获取指定头部字段
    std::string GetHeader(const std::string &key)const
    {
        auto it = _headers.find(key);
        if (it == _headers.end())
        {
            return "";
        }
        return it->second;
    }
    //设置正文
    void SetContent(const std::string& body,const std::string &type = "text/html"){
        _body = body;
        SetHeader("Content-Type", type);
    }
    //重定向设置
    void SetRedirect(const std::string&url,int statu = 302){
        _statu = statu;
        _redirect_url = url;
        _redirect_flag = true;
    }
    //判断是否是短链接
    bool Close()const{
        // 没有Connection字段，或者有Connection但是值是close，则都是短链接，否则就是长连接
        if (HasHeader("Connection") == true && GetHeader("Connection") == "keep-alive")
        {
            return false;
        }
        return true;
    }
};

typedef enum
{
    RECV_HTTP_ERROR,
    RECV_HTTP_LINE,
    RECV_HTTP_HEAD,
    RECV_HTTP_BODY,
    RECV_HTTP_OVER
} HttpRecvStatu;//获取request的不同状态
#define MAX_LINE 8192
class HttpContext
{
public:
    int _resp_statu;//响应的状态的
    HttpRecvStatu _recv_statu;
    HttpRequest _request;//上下文
private:

    //解析请求头
    bool ParseHttpLine(const std::string&line){
        std::smatch matches;
        std::regex e("(GET|HEAD|POST|PUT|DELETE) ([^?]*)(?:\\?(.*))? (HTTP/1\\.[01])(?:\n|\r\n)?", std::regex::icase);
        //忽略大小写
        bool ret = std::regex_match(line, matches, e);
        if(ret == false){
            DBG_LOG("here");
            _recv_statu = RECV_HTTP_ERROR;
            _resp_statu = 404;
            return false;

        }
        // 0 : GET /bitejiuyeke/login?user=xiaoming&pass=123123 HTTP/1.1
        // 1 : GET
        // 2 : /bitejiuyeke/login
        // 3 : user=xiaoming&pass=123123
        // 4 : HTTP/1.1
        _request._method = matches[1];
        //转换大小写，转成大写

        _request._path = Util::UrlDecode(matches[2], false);//url需要解码
        if(_request._path.empty())
            _request._path = "/";
        // 协议版本获取
        _request._version = matches[4];

        //查询字符串分割
        std::vector<std::string> query_string_array;
        std::string query_string = matches[3];
        //查询字符串的格式 key=val&key=val....., 先以 & 符号进行分割，得到各个字串
        Util::Split(query_string, "&", &query_string_array);
        //针对各个查询字符串，以=进行分割，得到key和val，得到之后也需要进行url解码
        for(auto &str:query_string_array){
            size_t pos = str.find("=");
            if(pos==std::string::npos){
                _recv_statu = RECV_HTTP_ERROR;
                _resp_statu = 400;
                return false;
            }
            std::string key = Util::UrlDecode(str.substr(0, pos),true);
            std::string val = Util::UrlDecode(str.substr(pos+1),true);
            _request.SetParam(key, val);
        }
        return true;
    }
    bool RecvHttpLine(Buffer*buf){
        if(_recv_statu!=RECV_HTTP_LINE)
            return false;
        std::string line = buf->GetLineAndPop();
        if(line.size()==0){
            //缓冲区中的数据不足一行，则需要判断挡墙缓冲区的可读数据长度
            //如果很长了都不足一行，这是有问题的
            //响应状态设为414
            if(buf->ReadAbleSize()>MAX_LINE){
                _recv_statu = RECV_HTTP_ERROR;
                _resp_statu = 414;//url too long
                return false;
            }
            return true;
        }
        if(line.size() > MAX_LINE){
            _recv_statu = RECV_HTTP_ERROR;
                _resp_statu = 414;//url too long
                return false;
        }
        
        //解析请求头
        bool ret = ParseHttpLine(line);
        if(ret==false){
            return false;
        }
        //请求头解析完成，进入获取头部阶段
        _recv_statu = RECV_HTTP_HEAD;
        return true;
    }

    //解析头部
    bool ParseHttpHead(std::string& line){
        if(line.back()=='\n')
            line.pop_back();
        if(line.back()=='\r')
            line.pop_back();
        size_t pos = line.find(":");
        if(pos==std::string::npos){
            _recv_statu = RECV_HTTP_ERROR;
            _resp_statu = 400;
            return 400;
        }
        std::string key = line.substr(0, pos);
        std::string val = line.substr(pos + 2);
        _request.SetHeader(key, val);
        return true;
    }
    bool RecvHttpHead(Buffer*buf){
        if(_recv_statu!=RECV_HTTP_HEAD)
            return false;
        while (1)
        {
            std::string line = buf->GetLineAndPop();
            if (line.size() == 0)
            {
                // 缓冲区中的数据不足一行，则需要判断挡墙缓冲区的可读数据长度
                // 如果很长了都不足一行，这是有问题的
                // 响应状态设为414
                if (buf->ReadAbleSize() > MAX_LINE)
                {
                    _recv_statu = RECV_HTTP_ERROR;
                    _resp_statu = 414; // url too long
                    return false;
                }
                return true;
            }
            if (line.size() > MAX_LINE)
            {
                _recv_statu = RECV_HTTP_ERROR;
                _resp_statu = 414; // url too long
                return false;
            }
            if(line=="\r\n" || line=="\n")
                break;
            // 解析请求头
            bool ret = ParseHttpHead(line);
            if (ret == false)
            {
                return false;
            }
        }
        // 头部解析完成，进入获取正文阶段
        _recv_statu = RECV_HTTP_BODY;
        return true;
    }

    bool RecvHttpBody(Buffer*buf){
        if(_recv_statu !=RECV_HTTP_BODY)
            return false;
        size_t real_len = _request.ContentLength() - _request._body.size();
        if(real_len > buf->ReadAbleSize()){
            _request._body.append(buf->ReadPosition(), buf->ReadAbleSize());
            buf->MoveReadOffset(buf->ReadAbleSize());
            return true;
        }
        _request._body.append(buf->ReadPosition(), real_len);
        buf->MoveReadOffset(real_len);
        return true;
    }
public:
    HttpContext():_resp_statu(200),_recv_statu(RECV_HTTP_LINE){}
    //重置
    void ReSet(){
        _request.ReSet();
        _resp_statu = 200;
        _recv_statu = RECV_HTTP_LINE;
    }
    //获取变量接口
    int RespStatu() { return _resp_statu; }
    HttpRecvStatu RecvStatu() { return _recv_statu; }
    HttpRequest &Request() { return _request; }

    //从上下文继续读取
    void RecvHttpRequest(Buffer*buf){
        switch (_recv_statu)
        {
        case RECV_HTTP_LINE:
            RecvHttpLine(buf);
        case RECV_HTTP_HEAD:
            RecvHttpHead(buf);
        case RECV_HTTP_BODY:
            RecvHttpBody(buf);
        }
        return;
    }
};
#define DEFALUT_TIMEOUT 10
class HttpServer{
private:
    using Handler = std::function<void(const HttpRequest&, HttpResponse*)>;
    using Handlers = std::vector<std::pair<std::regex, Handler>>;
    Handlers _get_route;
    Handlers _put_route;
    Handlers _post_route;
    Handlers _delete_route;
    std::string _basedir;//静态资源根目录表
    TCP_Server _server;

public:
    HttpServer(int port, int timeout = DEFALUT_TIMEOUT) : _server(port)
    {
        _server.EnableInactiveRelease(timeout);
        _server.SetConnectedCallback(std::bind(&HttpServer::OnConnected, this, std::placeholders::_1));
        _server.SetMessageCallback(std::bind(&HttpServer::OnMessage, this, std::placeholders::_1, std::placeholders::_2));
    }
    virtual ~HttpServer()
    {
    }
    void SetBasedir(const std::string &dir){
        assert(Util::IsDirectory(dir) == true);
        _basedir = dir;
    }
    void Get(const std::string &pattern, const Handler &handler){
        _get_route.push_back({std::regex(pattern), handler});
    }
    void Post(const std::string &pattern, const Handler &handler){
        _post_route.push_back({std::regex(pattern), handler});

    }
    void Put(const std::string &pattern, const Handler &handler){
        _put_route.push_back({std::regex(pattern), handler});

    }
    void Delete(const std::string &pattern, const Handler &handler){
        _delete_route.push_back({std::regex(pattern), handler});

    }
    void SetThreadCount(int n){
        _server.SetThreadCount(n);
    }
    virtual void Listen(){
        _server.Start();
    }
    
private:
    void ErrorHandler(const HttpRequest&req,HttpResponse*rsp){
        //1.组织展示一个错误页面
        std::string body;
        body += "<html>";
        body += "<head>";
        body += "<meta http-equiv='Content-Type' content='text/html;charset=utf-8'>";
        body += "</head>";
        body += "<body>";
        body += "<h1>";
        body += std::to_string(rsp->_statu);
        body += " ";
        body += Util::StatuDesc(rsp->_statu);
        body += "</h1>";
        body += "</body>";
        body += "</html>";

        //2.将页面数据，放入响应正文中
        rsp->SetContent(body);
    }
    // 设置上下文
    virtual void OnConnected(const PtrConnection&conn) {
        conn->SetContext(HttpContext());
        DBG_LOG("NEW CONNECTION %p", conn.get());
    }

    //解析缓冲区数据,制作req和rsp
    virtual void OnMessage(const PtrConnection&conn,Buffer*buf){
        //DBG_LOG("OnMessage here");
        while (buf->ReadAbleSize() > 0)
        { // 1.获取上下文
            HttpContext *context = conn->GetContext()->get<HttpContext>();
            // 2.根据上下文对缓冲区中数据进行解析，得到httprequest对象
            //   1.如果缓冲区的数据解析出错，就直接回复出错响应
            //   2.如果解析正常，且已经获取完毕，才开始进行处理
            context->RecvHttpRequest(buf);
            HttpRequest &req = context->Request();
            HttpResponse rsp(context->RespStatu());
            if (context->RespStatu() >= 400)
            {
                // 进行错误响应，关闭连接
                ErrorHandler(req, &rsp); // 将req中的错误信息填到rsp中
                // 后面不进行业务处理直接发送响应
                WriteResponse(conn, req, rsp);
                // 出错了把缓冲区数据清空和关闭连接
                context->ReSet();
                buf->Clear();
                conn->Shutdown();
                return;
            }
            // 3.请求路由+业务处理
            Route(req, &rsp);
            // 4.对httpreponse进行组织发送
            WriteResponse(conn, req, rsp);
            // 5.重置上下文
            context->ReSet();
            // 6.判断长短链接是否关闭连接或继续处理
            if (rsp.Close())
                conn->Shutdown(); // 短链接直接关闭
        }
    }
    void Route(HttpRequest&req,HttpResponse*rsp)//路由
    {
        //如果GET|HEAD方法先默认静态资源
        if(IsFileHandler(req)){
            FileHandle(req,rsp);
            return;
        }
        //如果不是静态资源就尝试功能性函数
        else if(req._method=="GET" || req._method == "HEAD"){
            Dispatcher(req, rsp, _get_route);
        }
        else if(req._method == "POST"){
            Dispatcher(req, rsp, _post_route);
        }
        else if(req._method == "PUT"){
            Dispatcher(req, rsp, _put_route);
        }
        else if(req._method == "DELETE"){
            Dispatcher(req, rsp, _delete_route);
        }
        else
            rsp->_statu = 405; // Method Not Allowed
        return;
    }
    //静态资源请求处理
    bool FileHandle(const HttpRequest&req,HttpResponse*rsp){
        //静态资源文件读取出来，放到rsp._body中，并设置mime
        //能进入处理说明已经经过验证，可直接获取
        //有个问题是这个路径要加上相对根目录，且需要判断是否是目录文件
        std::string path = _basedir + req._path;
        if(path.back()=='/')
            path += "index.html";
        bool ret = Util::ReadFile(path, &rsp->_body);
        if(ret==false)
            return false;   
        //在发送时会设置content-length
        rsp->SetHeader("Mime", Util::ExtMime(req._path));
        return true;
    }
    //功能性请求分类处理
    bool Dispatcher(HttpRequest&req,HttpResponse*rsp,Handlers&handlers){
        //由route路由过来
        //已经指定了某一个get/post...方法簇
        //在对应请方法的路由表中，查找是否含有对应资源请求的处理函数，有则调用，没有则发挥404
        //思想：路由表存储的键值对 --- 正则表达式&处理函数
        //使用正则表达式，对资源请求的资源路径进行正则匹配，匹配成功就使用对应函数进行处理
        // /numbers/(\d+)  /numbers/12345
        for(auto &handler:handlers){
            const std::regex &re = handler.first;
            const Handler &functor = handler.second;
            bool ret = std::regex_match(req._path, req._matches, re);
            if(ret == false)
                continue;
            functor(req,rsp);
            return true;
        }
        rsp->_statu = 404;//找不到服务
        return false;
    }

    //将rsp中的要素按http中的格式进行组织，发送
    void WriteResponse(const PtrConnection&conn,const HttpRequest&req, HttpResponse&rsp){
        //DBG_LOG("WriteResponse here");
        // 1.先完善头部字段
        // 长短链接
        // 正文长度
        // 正文类型
        // 是否重定向
        if(req.Close()){
            rsp.SetHeader("Connection", "close");
        }
        else{
            rsp.SetHeader("Connection", "keep-alive");
        }
        if(req._body.empty() == false && rsp.HasHeader("Content-Length")==false){
            rsp.SetHeader("Content-Length", std::to_string(rsp._body.size()));
        }
        if(req._body.empty() == false && rsp.HasHeader("Content-Type")==false){
            rsp.SetHeader("Content-Type", "application/octet-stream");
        }
        if(rsp._redirect_flag==true){
            rsp.SetHeader("Location", rsp._redirect_url.c_str());
        }
        //2.将rsp中的要素按http中的格式进行组织
        //流式写入
        //版本 状态码 状态描述
        //头部
        //
        //正文
        std::stringstream rsp_str;
        rsp_str << req._version << " " << std::to_string(rsp._statu) 
        << " " << Util::StatuDesc(rsp._statu)<<"\r\n";
        for(auto [key,val]:rsp._headers){
            rsp_str << key << ":" << val << "\r\n";
        }
        rsp_str << "\r\n";
        rsp_str << rsp._body;
        // 3.发送
        conn->Send(rsp_str.str().c_str(),rsp_str.str().size());
        //DBG_LOG("%s",rsp_str.str().c_str());
    }

    //判断httprequest请求是否是静态资源
    bool IsFileHandler(const HttpRequest &req){
        //1.必须设置了basedir
        if(_basedir.empty())
            return false;
        // 2.请求方法，必须是GET|POST
        if(req._method!="GET" && req._method!="POST")
            return false;
        // 3.路径必须合法
        if(Util::ValidPath(req._path)==false)
            return false;
        // 4.资源必须存在,且是一个普通文件
        //目录文件比较特殊，在后面默认追加一个 index.html
        //如/image -> /image/index.html
        //资源实际路径是  请求路径+相对根目录
        std::string req_path = _basedir + req._path;//为了避免修改req的path,因此创建一个临时变量
        if(req._path.back()=='/')
            req_path += "index.html";
        if(Util::IsRegular(req_path)==false)
            return false;
        return true;
    }

};